package com.bootdo.common.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import com.bootdo.common.vo.GpsInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class YinYanUtils {
    private static final String AK = "8MGH8dGiGGuM5ESRM59y9AdhPShIeypG";
    private static final String SERVICEID = "214679";



	/*
	private static final String AK = "XNAY6QxZTMauIl5jsNuAcCPWxLMHOSlE";
	private static final String SERVICEID = "204573";*/

    private static Logger logger = LoggerFactory.getLogger(YinYanUtils.class);
    //添加实体
    private static final String  addEntiy = "http://yingyan.baidu.com/api/v3/entity/add";
    //添加坐标 单个添加
    private static final String  addPoint = "http://yingyan.baidu.com/api/v3/track/addpoint";
    //得到最近一次上传的坐标
    private static final String getlatestpoint
            = "http://yingyan.baidu.com/api/v3/track/getlatestpoint?ak="+
            AK+"&service_id="+SERVICEID
            + "&is_processed=1"
            +"&coord_type_output=gcj02"
            + "&need_denoise=1,need_vacuate=0,need_mapmatch=1,radius_threshold=100,transport_mode=auto&supplement_mode=driving"
            + "&entity_name=";

    //根据时间 查询  路程的所有的坐标
    private static final String gettrack
            ="http://yingyan.baidu.com/api/v3/track/gettrack?ak="+
            AK+"&service_id="+SERVICEID+"&coord_type_output=gcj02"
            + "&is_processed=1"
            + "&need_denoise=1,need_vacuate=0,need_mapmatch=1,radius_threshold=100,transport_mode=auto&supplement_mode=driving"
            + "&entity_name=";


    public static void main(String []args) throws Exception{

        addEntiy(-1l);
        GpsInfo gps = new GpsInfo();

        //gps.setTimes(new Date().getTime()/ 1000);

		/*	gps.setLon(114.43732259114583);
		gps.setLat(36.63135579427083);
		gps.setLon(114.43726996527778);
		gps.setLat(36.63339870876736);*/


		/*gps.setLon(114.43835205078125);
		gps.setLat(36.630976019965274);

		addpoint(1l, gps);*/
		/*GpsInfo g = getlatestpoint(1l);
		if(null != g){
			System.out.println(g.getLat() + "\r" + g.getLon());
		}*/
        //sendGet("http://yingyan.baidu.com/api/v3/entity/list?ak=8MGH8dGiGGuM5ESRM59y9AdhPShIeypG&service_id=200937");
		/*Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1);
		gettrack(43l,calendar.getTime().getTime(), new Date().getTime());*/

    }








    /**
     * 发送PSOT请求
     * @return
     * @throws Exception
     */
    private static String sendPost(String path,Map map) throws Exception{
        String parm = toQueryString(map);
        System.out.println(parm);
        HttpURLConnection httpConn = null;
        BufferedReader in = null;
        BufferedWriter out = null;
        URL url=new URL(path);
        httpConn=(HttpURLConnection)url.openConnection();
        httpConn.setRequestMethod("POST");
        // 设置使用标准编码格式编码参数的名-值对
        httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        httpConn.setDoInput(true);
        httpConn.setDoOutput(true);
        //发送post请求参数
        out=new BufferedWriter(new OutputStreamWriter(httpConn.getOutputStream(), "UTF-8"));
        out.write(parm);
        out.flush();
        out.close();
        //读取响应
        if(httpConn.getResponseCode()==HttpURLConnection.HTTP_OK){
            StringBuffer content=new StringBuffer();
            String tempStr="";
            in=new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            while((tempStr=in.readLine())!=null){
                content.append(tempStr);
            }
            String str1 = new String(content.toString().getBytes("utf-8"),"utf-8");
            System.out.println(str1);
            return str1;
        }
        return null;
    }


    /**
     * 发送Get请求
     * @return
     * @throws Exception
     */
    private static String sendGet(String path) throws Exception{
        HttpURLConnection httpConn = null;
        BufferedReader in = null;
        BufferedWriter out = null;
        URL url=new URL(path);
        httpConn=(HttpURLConnection)url.openConnection();
        httpConn.setRequestMethod("GET");
        // 设置使用标准编码格式编码参数的名-值对
        httpConn.setDoInput(true);
        httpConn.setDoOutput(true);

        //读取响应
        if(httpConn.getResponseCode()==HttpURLConnection.HTTP_OK){
            StringBuffer content=new StringBuffer();
            String tempStr="";
            in=new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            while((tempStr=in.readLine())!=null){
                content.append(tempStr);
            }
            String str1 = new String(content.toString().getBytes("utf-8"),"utf-8");
            System.out.println(str1);
            return str1;
        }
        return null;
    }




    // 对Map内所有value作utf8编码，拼接返回结果
    private static String toQueryString(Map<?, ?> data) throws UnsupportedEncodingException {
        StringBuffer queryString = new StringBuffer();
        for (Entry<?, ?> pair : data.entrySet()) {
            queryString.append(pair.getKey() + "=");
            queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8") + "&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }
        return queryString.toString();
    }




    /**
     * 添加一个实体类
     * @param strokeRecordId
     * @return
     */
    public static boolean addEntiy(Long strokeRecordId){
        String entiyId  = getEntiyId(strokeRecordId);
        Map map = new TreeMap();
        map.put("ak",AK);
        map.put("service_id", SERVICEID);
        map.put("entity_name", entiyId);
        String str = null;
        try {
            str =  sendPost(addEntiy, map);
        } catch (Exception e) {
            logger.error("保存鹰眼实体出错"+e.getMessage());
            e.printStackTrace();
        }


        if(null != str){
            JSONObject json = JSONObject.parseObject(str);
            if(json.containsKey("status") && json.getIntValue("status") == 0){
                return true;
            }else{
                logger.error("保存鹰眼实体出错__状态不等于0");
                return false;
            }
        }
        return false;

    }




    /**
     * 添加GPS信息
     * @param strokeRecordId
     * @param gpsInfo
     * @return
     */
    public static boolean addpoint(Long strokeRecordId,GpsInfo gpsInfo){
        String entiyId  = getEntiyId(strokeRecordId);
        Map map = new TreeMap();
        map.put("ak",AK);
        map.put("service_id", SERVICEID);
        map.put("entity_name", entiyId);
        map.put("latitude", gpsInfo.getLat()+"");
        map.put("longitude",  gpsInfo.getLon()+"");
        map.put("loc_time",  gpsInfo.getTimes()+"");
        map.put("coord_type_input", "gcj02");
        String str = null;
        try {
            str = sendPost(addPoint, map);
            System.out.println("鹰眼保存的数据======="+str);
        } catch (Exception e) {
            logger.error("保存鹰眼坐标点出错"+e.getMessage());
            e.printStackTrace();
        }
        if(null != str){
            JSONObject json = JSONObject.parseObject(str);
            if(json.containsKey("status") && json.getIntValue("status") == 0){
                return true;
            }
        }
        return false;
    }


    /**
     * 得到最近上传的一次gps信息
     * @param strokeRecordId
     * @return
     */
    public static GpsInfo getlatestpoint(Long strokeRecordId){
        String entiyId  = getEntiyId(strokeRecordId);
        String str = null;
        try {
            str = sendGet(getlatestpoint+entiyId);
            System.out.println("鹰眼得到的数据======="+str);
        } catch (Exception e) {
            logger.error("得到最近的鹰眼坐标点出错"+e.getMessage());
            e.printStackTrace();
        }
        if(null != str){
            JSONObject json = JSONObject.parseObject(str);
            if(json.containsKey("status") && json.getIntValue("status") == 0){
                System.out.println("鹰眼得到的数据===初始化对象"+str);
                if(json.containsKey("latest_point")){
                    JSONObject temp = json.getJSONObject("latest_point");
                    if(null != temp){
                        GpsInfo gpsInfo = new GpsInfo();
                        if(temp.containsKey("longitude")&&temp.containsKey("latitude")){
                            gpsInfo.setLat(temp.getDoubleValue("latitude"));
                            gpsInfo.setLon(temp.getDoubleValue("longitude"));

                            return gpsInfo;
                        }
                    }
                }
            }
        }
        return null;
    }


    /**
     * 得到一段时间的路程信息
     * @param strokeRecordId
     * @return
     */
    public static List<GpsInfo>  gettrack(Long strokeRecordId ,Long startTime , Long endTime){
        List<GpsInfo> resultList =  new ArrayList<GpsInfo>();
        String entiyId  = getEntiyId(strokeRecordId);
        startTime = (startTime/1000);
        endTime = (endTime/1000);
        System.out.println(startTime+"=="+endTime);
        String str = null;
        try {
            String url = gettrack+entiyId+"&start_time="+startTime+"&end_time="+endTime;
            str = sendGet(url);
        } catch (Exception e) {
            logger.error("得到最近的鹰眼坐标点出错"+e.getMessage());
            e.printStackTrace();
        }
        if(null != str){
            JSONObject json = JSONObject.parseObject(str);
            if(json.containsKey("status") && json.getIntValue("status") == 0){
                GpsInfo gpsInfo = new GpsInfo();
                if(json.containsKey("points")){
                    JSONArray array = json.getJSONArray("points");
                    if(null != array){
                        for(int i = 0; i < array.size(); i++){
                            JSONObject j= (JSONObject) array.get(i);
                            if(j.containsKey("latitude") && j.containsKey("longitude")){
                                GpsInfo gps = new GpsInfo();
                                gps.setLat(j.getDoubleValue("latitude"));
                                gps.setLon(j.getDoubleValue("longitude"));
                                resultList.add(gps);
                            }
                        }
                        return resultList;
                    }
                }
            }
        }


        return null;
    }



    /**
     * 得到实体ID
     * @param strokeRecordId
     * @return
     */
    public static String getEntiyId(Long strokeRecordId){
        return "strokeRecord_linzhang"+strokeRecordId;
    }



}
